import { getStaff } from '@/common/api/auth'

const state = {
  staff: [],
}

const getters = {
  staff: state => state.staff,
}
let isGet = false
const actions = {
  getStaff({ commit }, force = false) {
    return new Promise((resolve, reject) => {
      if (!force && state.staff.length) {
        resolve(state.staff)
        return
      }
      if (isGet) {
        resolve(state.staff)
      } else {
        isGet = true
        getStaff()
          .then(res => {
            const data = (res && res.data) || []
            commit('setStaff', data)
            resolve(data)
          })
          .catch(err => {
            reject(err)
          })
          .finally(() => {
            isGet = false
          })
      }
    })
  },
}

const mutations = {
  setStaff: (state, payload) => (state.staff = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
